package com.piya;

import static com.taobao.weex.WXEnvironment.getApplication;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import org.opencv.android.OpenCVLoader;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.objdetect.CascadeClassifier;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;

public class FaceDetectionHelper extends UniModule {

    private static final String TAG = "FaceDetectionHelper";

    // 异步检测
    @UniJSMethod(uiThread = true)
    public void testAsyncFunc(JSONObject options, final UniJSCallback callback) {
        // 加载OpenCV库
        if (!OpenCVLoader.initDebug()) {
            Log.e(TAG, "OpenCV初始化失败");
            if (callback != null) {
                JSONObject errorData = new JSONObject();
                errorData.put("error", "OpenCV初始化失败");
                callback.invoke(errorData);
            }
            return;
        }

        // 加载人脸检测器模型
        CascadeClassifier cascadeClassifier = loadCascadeClassifier();

        if (cascadeClassifier == null) {
            Log.e(TAG, "级联分类器加载失败");
            if (callback != null) {
                JSONObject errorData = new JSONObject();
                errorData.put("error", "级联分类器加载失败");
                callback.invoke(errorData);
            }
            return;
        }

        // 获取图片URL
        String imageUrl = options.getString("imgUrl");

        // 下载并处理图片
        new AsyncTask<String, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(String... params) {
                try {
                    URL url = new URL(params[0]);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    InputStream input = connection.getInputStream();
                    return BitmapFactory.decodeStream(input);
                } catch (Exception e) {
                    Log.e(TAG, "下载图像时出错: " + e.getMessage());
                    return null;
                }
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                if (bitmap != null) {
                    // 在图像上执行人脸检测
                    JSONObject resultData = detectFaces(bitmap, cascadeClassifier);

                    // 调用回调函数返回检测结果
                    if (callback != null) {
                        callback.invoke(resultData);
                    }
                } else {
                    Log.e(TAG, "下载图像时出错");
                    if (callback != null) {
                        JSONObject errorData = new JSONObject();
                        errorData.put("error", "下载图像时出错");
                        callback.invoke(errorData);
                    }
                }
            }
        }.execute(imageUrl);
    }

    // 加载人脸检测器模型
    private CascadeClassifier loadCascadeClassifier() {
        try {
            InputStream is = getApplication().getApplicationContext().getAssets().open("haarcascade_frontalface_alt.xml");
            File cascadeFile = new File(getApplication().getApplicationContext().getCacheDir(), "haarcascade_frontalface_alt.xml");
            FileOutputStream os = new FileOutputStream(cascadeFile);
            //获取模型
            byte[] buffer = new byte[40960];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            is.close();
            os.close();

            CascadeClassifier cascadeClassifier = new CascadeClassifier(cascadeFile.getAbsolutePath());
            if (cascadeClassifier.empty()) {
                return null;
            }

            return cascadeClassifier;
        } catch (Exception e) {
            Log.e(TAG, "加载级联分类器时出错: " + e.getMessage());
            return null;
        }
    }

    // 在图像上执行人脸检测
    private JSONObject detectFaces(Bitmap bitmap, CascadeClassifier cascadeClassifier) {
        Mat mat = new Mat();
        MatOfRect faces = new MatOfRect();

        // 将Bitmap转换为OpenCV的Mat对象
        org.opencv.android.Utils.bitmapToMat(bitmap, mat);

        // 执行人脸检测
        cascadeClassifier.detectMultiScale(mat, faces);

        // 构建JSON对象来保存检测结果
        JSONObject resultData = new JSONObject();
        JSONArray facesArray = new JSONArray();
        resultData.put("数量", faces.toArray().length);
        Rect[] rectsArray = faces.toArray();
        for (Rect rect : rectsArray) {
            JSONObject faceData = new JSONObject();
            faceData.put("height", rect.height);
            faceData.put("x", rect.x);
            faceData.put("width", rect.width);
            faceData.put("y", rect.y);
            facesArray.add(faceData);
        }
        resultData.put("位置",facesArray);

        JSONObject res = new JSONObject();
        res.put("code","success");
        res.put("data",resultData);
        return res;
    }
}
